<template>
  <view class="container">
    <!-- 未登录状态 -->
    <view v-if="!isLoggedIn" class="login-card">
      <button 
        class="wx-login-btn" 
        open-type="getUserInfo"
        @getuserinfo="handleUserInfo"
      >
        微信登录
      </button>
    </view>
    
    <!-- 已登录状态 -->
    <view v-else class="profile-card">
      <image 
        class="avatar" 
        :src="avatarUrl" 
        mode="aspectFill"
      ></image>
      <view class="user-info">
        <text class="username">{{  userInfo.nikeName || userInfo.nickName || '微信用户' }}</text>
        <!-- <text class="phone" v-if="userInfo.phone">{{ userInfo.phone }}</text> -->
        <!-- <text class="no-phone" v-else>未绑定手机号</text> -->
      </view>
      <!-- <button 
        v-if="!userInfo.phone"
        class="bind-phone-btn"
        open-type="getPhoneNumber"
        @getphonenumber="handlePhoneNumber"
      >
        绑定手机号
      </button> -->
    </view>
    
    <view class="mine-list">
      <uni-list>
        <uni-list-item 
          v-for="item in displayMenuItems" 
          :key="item.id"
          :id="item.id" 
          :title="item.title" 
          :thumb="item.icon"
          showArrow 
          clickable
          @click="onItemClick(item.id)"
        >
          <template v-slot:header>
            <view class="list-icon">
              <image class="list-icon__img" :src="item.icon" mode="aspectFit" />
            </view>
          </template>
        </uni-list-item>
      </uni-list>
    </view>
  </view>
</template>

<script>
import { API,config } from '@/utils/api.js'
import { isMiniProgram, wxLogin, showModal } from '@/utils/miniprogram.js'

export default {
  data() {
    return {
      isLoggedIn: false,
      userInfo: {},
      menuItems: [
        { id: 1, title: '我的信息', icon: '/static/assets/me/me-message.png' },
        { id: 2, title: '我的预约', icon: '/static/assets/me/me-sub.png' },
        { id: 3, title: '我的收藏', icon: '/static/assets/me/me-favorite.png' },
        { id: 4, title: '联系我们', icon: '/static/assets/me/me-connet.png' },
        // { id: 5, title: '在线客服', icon: '/static/assets/me/me-lineserver.png' },
      ]
    }
  },
  computed: {
    displayMenuItems() {
      return this.menuItems.filter(i => !i.onlyWhenLoggedIn || this.isLoggedIn)
    }, 
    avatarUrl() {
      if (!this.userInfo.headPicture) return ''
      // 如果是http或https开头，直接返回
      if (/^https?:\/\//.test(this.userInfo.headPicture)) {
        return this.userInfo.headPicture
      }
      // 否则拼接服务器地址
      // 兼容 / 开头和无 / 开头
      if (this.userInfo.headPicture.startsWith('/')) {
        return config.baseURL + this.userInfo.headPicture
      } else {
        return config.baseURL + '/' + this.userInfo.headPicture
      }
    }   
  },
  
  onShow() {
    this.checkLoginStatus()
  },
  mounted() {
    this.checkLoginStatus()
  },
  
  methods: {
    // 获取微信登录code
    getCode() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            reject(err);
          }
        })
      })
    },
    
    // 获取微信用户信息
    getUserInfo() {
      return new Promise((resolve, reject) => {
        uni.getUserInfo({
          provider: 'weixin',
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            reject(err);
          }
        })
      })
    },
    
    // 检查登录状态
    checkLoginStatus() {
      const userInfo = uni.getStorageSync('userInfo')
      const token = uni.getStorageSync('user-token')
      console.log('userInfo', userInfo)
      console.log('token', token)
      if (userInfo && token) {
        this.isLoggedIn = true
        this.userInfo = JSON.parse(userInfo)
      } else {
        this.isLoggedIn = false
        this.userInfo = {}
      }
    },
    
    // 清除登录信息
    clearLoginInfo() {
      uni.removeStorageSync('user-token')
      uni.removeStorageSync('userInfo')
      this.isLoggedIn = false
      this.userInfo = {}
    },
    
    // 处理微信用户信息授权
    async handleUserInfo(e) {
      if (e.detail.errMsg !== 'getUserInfo:ok') {
        uni.showToast({
          title: '需要授权才能使用',
          icon: 'none'
        })
        return
      }
      
      try {
        // 获取微信登录code
        const codeRes = await this.getCode()
        
        // 发送登录请求
        const loginData = {
          code: codeRes.code,
          nickName: e.detail.userInfo.nickName,
          avatarUrl: e.detail.userInfo.avatarUrl,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        }
        
        const result = await API.auth.wxLogin(loginData)
        
        // 保存登录信息
        if (result && result.token) {
          // 修复：token 直接保存，不需要 JSON.stringify
          uni.setStorageSync('user-token', result.token)
          uni.setStorageSync('userInfo', JSON.stringify(result.userInfo))
          
          this.isLoggedIn = true
          this.userInfo = result.userInfo
          // 关闭登录弹窗
          // this.closeLoginPopup() // This line was not in the original file, so it's removed.
          
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })
          
          // 执行待执行的操作
          // if (this.pendingAction) { // This line was not in the original file, so it's removed.
          //   this.executeAction(this.pendingAction)
          //   this.pendingAction = null
          // }
        } else {
          throw new Error('登录接口返回数据异常')
        }
        
      } catch (error) {
        console.error('微信登录失败:', error)
        uni.showToast({
          title: '登录失败，请重试',
          icon: 'none'
        })
      }
    },
    
    // 处理手机号授权
    async handlePhoneNumber(e) {
      if (e.detail.errMsg !== 'getPhoneNumber:ok') {
        uni.showToast({
          title: '需要手机号授权',
          icon: 'none'
        })
        return
      }
      
      try {
        const phoneData = {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        }
        
        const result = await API.auth.decryptPhone(phoneData)
        
        // 更新用户信息
        if (result && result.data && result.data.phone) {
          const updatedUserInfo = {
            ...this.userInfo,
            phone: result.data.phone
          }
          
          uni.setStorageSync('userInfo', updatedUserInfo)
          this.userInfo = updatedUserInfo
          
          uni.showToast({
            title: '手机号绑定成功',
            icon: 'success'
          })
        } else {
          throw new Error('手机号绑定接口返回数据异常')
        }
        
      } catch (error) {
        console.error('手机号绑定失败:', error)
        uni.showToast({
          title: '绑定失败，请重试',
          icon: 'none'
        })
      }
    },
    
    // 退出登录
    async logout() {
      const result = await showModal({
        title: '确认退出',
        content: '确定要退出登录吗？'
      })
      
      if (result.confirm) {
        // 清除本地存储
        this.clearLoginInfo()
        
        uni.showToast({
          title: '已退出登录',
          icon: 'success'
        })
      }
    },
    onItemClick(id) {
      // 需要登录的功能检查
      if ([1, 2, 3].includes(id) && !this.isLoggedIn) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      // 根据不同id跳转或处理
      switch(id) {
        case 1:
          uni.navigateTo({ url: '/pages/mine/myInfo' });
          break;
        case 2:
          uni.navigateTo({ url: '/pages/mine/myReserve' });
          break;
        case 3:
          uni.navigateTo({ url: '/pages/mine/myFavorite' });
          break;
        case 4:
          this.contactUs();
          break;
        case 5:
          this.openCustomerService();
          break;
        case 6:
          this.logout();
          break;
        default:
          uni.showToast({ title: '未知操作', icon: 'none' });
      }
    },
    
    // 联系我们
    contactUs() {
      uni.makePhoneCall({
        phoneNumber: '021-31575228'
      })
    },
    
    // 在线客服
    openCustomerService() {
      if (isMiniProgram()) {
        // 小程序环境打开客服会话
        // #ifdef MP-WEIXIN
        uni.openCustomerServiceChat({
          extInfo: {
            url: 'https://work.weixin.qq.com/kfid/xxx'
          },
          corpId: 'corpid',
          success: function(res) {
            console.log('打开客服会话成功')
          },
          fail: function(err) {
            console.error('打开客服会话失败', err)
            uni.showToast({
              title: '客服暂时不可用',
              icon: 'none'
            })
          }
        })
        // #endif
      } else {
        uni.showToast({
          title: '客服功能仅在小程序中可用',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.container {
  background: #ffffff;
  min-height: 100vh;
  /* padding-bottom: 100rpx; */
}

/* 未登录状态样式 */
.login-card {
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 32rpx;
}

.avatar-placeholder {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-bottom: 24rpx;
  opacity: 0.6;
}

.login-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.wx-login-btn {
  background: #07c160;
  color: white;
  border: none;
  border-radius: 44rpx;
  height: 88rpx;
  width: 300rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
}

.wx-login-btn::after {
  border: none;
}

.wx-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 16rpx;
}

/* 已登录状态样式 */
.profile-card {
  /* background: #fff; */
  margin: 0 16rpx 16rpx 16rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  padding: 32rpx;
  position: relative;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-right: 24rpx;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 36rpx;
  color: #3F3F3F;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.phone {
  font-size: 28rpx;
  color: #666;
}

.no-phone {
  font-size: 28rpx;
  color: #999;
}

.bind-phone-btn {
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 32rpx;
  height: 64rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  position: absolute;
  right: 32rpx;
}

.bind-phone-btn::after {
  border: none;
}

.mine-list {
  background-color: #fff;
  border-radius: 30rpx 30rpx 0 0;
  padding: 20rpx;
  height: 100%;
  min-height: 1200rpx; /* 填充空间，防止内容过少时塌陷 */
  box-sizing: border-box;
}

/* 图标背景包装 */
.list-icon {
  width: 82rpx;
  height: 82rpx;
  border-radius: 16rpx;
  background-image: url('/static/assets/me/me-icon-bg.png');
  background-size: 100% 100%;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.list-icon__img {
  width: 36rpx;
  height: 36rpx;
  object-fit: contain;
  margin-bottom: 10rpx;
}
</style>